// 获取DOM元素
const fileInput = document.getElementById("fileInput");
const confirmBtn = document.getElementById("confirmBtn");
const uploadButton = document.getElementById("uploadButton");
const uploadBtnImg = document.querySelector(".upload-btn-img");
const uploadedImageContainer = document.getElementById(
  "uploadedImageContainer"
);
const uploadedImage = document.getElementById("uploadedImage");
const backBtn = document.querySelector(".back-btn"); // 返回按钮

// 返回按钮功能：点击返回上一页
backBtn.addEventListener("click", () => {
  window.history.back();
});

// 上传按钮点击事件
uploadBtnImg.addEventListener("click", (e) => {
  e.stopPropagation();
  fileInput.click();
});

// 监听文件选择变化
fileInput.addEventListener("change", (e) => {
  const file = e.target.files[0];
  if (!file) return;

  if (!file.type.startsWith("image/")) {
    alert("请选择图片文件（JPG/PNG等）");
    return;
  }

  const reader = new FileReader();
  reader.onload = (event) => {
    uploadButton.style.display = "none";
    uploadedImageContainer.style.display = "block";
    uploadedImage.src = event.target.result;
  };
  reader.readAsDataURL(file);

  confirmBtn.disabled = false;
});


// 确定按钮事件
confirmBtn.addEventListener("click", () => {
  const file = fileInput.files[0];
  if (!file) {
    alert("请先上传图片");
    return;
  }

  const formData = new FormData();
  formData.append("image", file);

  alert(`图片 "${file.name}" 已准备上传，即将调用后端接口`);

  // 真实接口调用示例：
  
  fetch("http://127.0.0.1:5000/api/upload/image", {
    method: "POST",
    body: formData
  })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert("图片上传成功！");
      } else {
        alert("叮叮：" + data.message);
      }
    })
    .catch(err => {
      console.error("上传出错：", err);
      alert("网络错误，请重试");
    });
  
});
